import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Text,
    Image,
    TextInput,
    TouchableOpacity,
    SafeAreaView,
    ScrollView,
} from 'react-native';
import DateTimePicker from "react-native-modal-datetime-picker";
import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import { Formik } from 'formik';
import moment from 'moment';
import { RRCLoading, RRCToast } from 'react-native-overlayer';
import BaseComponent from '../component/BaseComponent';
import HttpUtil from '../util/HttpUtil';
import BranchTree from '../component/BranchTree';
import UserTree from '../component/UserTree';
import Area from '../component/Area';
import TypeTree from '../component/TypeTree';
import BrandTree from '../component/BrandTree';
import ModelTree from '../component/ModelTree';
import Reason from '../component/Reason';
import RemarkTree from '../component/RemarkTree';

export default class AddInventory extends BaseComponent {

    constructor(props){
        super(props);
        this.state={
            showManageBranchModal: false,
            showManageUserModal: false,
            showAreaModal: false,
            showTypeModal: false,
            isDateTimePickerVisible: false,
            showBrandModal: false,
            branchList:[],
            selectUserList: [],
            datacenterRoomTree:[],
            typeList:[],
            brandModeList: [],
            modeList: [],
            moveReasonList:[],
            remarkList: [],
            inventoryName: '',
            manageBranchName: '',
            manageBranchId: '',
            manageUserName:'',
            manageUser: '',
            remark:'',
            roomType: '',
            areaName: '',
            areaId: '',
            dataCenterId: '',
            finishDate:'',
            typeName: '',
            typeId: '',
            brandId: '',
            brandName: '',
            showModelModal: false,
            modelName: '',
            modelId: '',
            showReasonModal: false,
            reasonName: '',
            reasonId: '',
            showReasonModal: false,
            showRemarkModal: false,
            assetRemark: '',
        }
    }

    componentDidMount() {
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })
        RRCLoading.show();
        this.init();        
    }

    onBackClicked = () => {
        this.props.navigation.navigate('Inventory');
        this.props.navigation.state.params.callBack();
        return true;
    }

    back = () =>{
        this.props.navigation.navigate('Inventory');
        this.props.navigation.state.params.callBack();
    }

    init = () => {
       
        HttpUtil.post('basicData', null)
        .then(result => {     
            if(result.httpCode == 200){
                this.setState({
                    datacenterRoomTree: result.data.datacenterRoomTree,
                    //cabinetList: result.data.cabinetList,
                    branchList: result.data.departmentTree,
                    userList: result.data.userList,
                    brandModeList: result.data.brandModelTree,
                    typeList: result.data.typeVo,
                    // roomList: result.data.datacenterRoomTree,
                    // branchList: result.data.departmentTree,
                    // userList: result.data.userList,
                    moveReasonList: result.data.moveReasonList,
                    remarkList: result.data.remarkList,
                });
                RRCLoading.hide();
            }else{
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 3000);
            }
        })
        .catch(error => {
            RRCLoading.hide();
            RRCToast.show('系统异常', 1, 3000);
        })
    }

    handleChange = (field) => {
        this.setState(field);
    }

    openManageBranchModal = () => {
        this.setState({
            showManageBranchModal: true,
        });
    }

    closeManageBranchModal = () => {
        this.setState({
            showManageBranchModal: false,
        });
    }

    selectManageBranch = (branch) => {
        //if(branch.isEnd){
            this.setState({
                manageBranchName: branch.name,
                manageBranchId: branch.id_,
                showManageBranchModal: false,
                manageUserName:'',
                manageUser: '',
            });
        //} 
    }

    openManageUserModal = () => {
        let selectUserList = [];
        this.state.userList.forEach((value) => {
            //console.log(value.name);
            if(this.state.manageBranchId == value.deptId_){
                selectUserList.push(value);
            }
        });
        this.setState({
            selectUserList: selectUserList,
            showManageUserModal: true,
        });
    }

    closeManageUserModal = () => {
        this.setState({
            showManageUserModal: false,
        });
    }

    selectManageUser = (user) => {
        this.setState({
            manageUserName: user.name,
            manageUser: user.id_,
            showManageUserModal: false,
        });
    }

    openAreaModal = () => {
        this.setState({
            showAreaModal: true,
        });
    }

    closeAreaModal = () => {
        this.setState({
            showAreaModal: false,
        });
    }

    selectArea = ( area ) => {
        if(area.isRoom){
            this.setState({
                roomType: area.roomType,
                areaName: area.label,
                areaId: area.value,
                dataCenterId: area.dataCenterId,
                showAreaModal: false,
            });
        }
    }

    showDateTimePicker = () => {
        this.setState({ isDateTimePickerVisible: true });
    };
    
    hideDateTimePicker = () => {
        this.setState({ isDateTimePickerVisible: false });
    };
    
    handleDatePicked = date => {
        this.setState({ finishDate: moment(date).format("YYYY-MM-DD") });
        this.hideDateTimePicker();
    };

    submit = () => {

        if(!this.state.inventoryName.trim()){
            RRCToast.show('请填写盘点名称', 2, 3000);
            return;
        }
        if(this.state.inventoryName.length > 20){
            RRCToast.show('盘点名称长度不能超过20个字符', 2, 3000);
            return;
        }
        if(this.state.remark.length > 200){
            RRCToast.show('备注长度不能超过200个字符', 2, 3000);
            return;
        }
        if(!this.state.finishDate){
            RRCToast.show('请选择盘日期', 2, 3000);
            return;
        }
        if(!this.state.areaId){
            RRCToast.show('请选择盘点位置', 2, 3000);
            return;
        }
        if(!this.state.manageUser){
            RRCToast.show('请选择盘点人', 2, 3000);
            return;
        }
        if(!this.state.finishDate){
            RRCToast.show('请选择盘日期', 2, 3000);
            return;
        }
  
        let params = {
            inventoryName: this.state.inventoryName.trim(),
            inventoryType: 2,
            roomId: this.state.areaId,
            remark: this.state.remark,
            operatiorBy: this.state.manageUser,
            beginTime: this.state.finishDate,
            typeId: this.state.typeId,
            brandId: this.state.brandId,
            modelId: this.state.modelId,
            assetStatusId: this.state.reasonId,
            assetRemark: this.state.assetRemark,
        }
        //console.log(params);
        RRCLoading.setLoadingOptions({
            text: '请稍候',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: {backgroundColor: 'rgba(0,0,0,0.8)'},
            loadingTextStyle: {}
        })
        RRCLoading.show();
        //console.log(params);
        HttpUtil.post('createInventory', params)
            .then(result => { 
                //console.log(result);
                if(result.httpCode == 200){ 
                    RRCToast.show('保存成功', 2, 5000);
                    RRCLoading.hide();
                    this.props.navigation.navigate('Inventory');
                    this.props.navigation.state.params.callBack();
                }else{
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 5000);
                }
            })
            .catch(error => {
                //console.log(error);
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 5000);
            })


    }

    openTypeModal = () => {
        this.setState({
            showTypeModal: true,
        });
    }

    closeTypeModal = () => {
        this.setState({
            showTypeModal: false,
        });
    }

    selectType = (type) => {
        this.setState({
            typeName: type.name,
            typeId: type.id_,
            showTypeModal: false,
        });
    }

    openBrandModal = () => {
        this.setState({
            showBrandModal: true,
        });
    }

    closeBrandModal = () => {
        this.setState({
            showBrandModal: false,
        });
    }

    selectBrand = (model) => {
        this.setState({
            brandName: model.label,
            brandId: model.value,
            showBrandModal: false,
        });
        this.setState({
            modeList: model.children,
        });
    }

    openModelModal = () => {
        this.setState({
            showModelModal: true,
        });
    }

    closeModelModal = () => {
        this.setState({
            showModelModal: false,
        });
    }

    selectModel = (model) => {
        this.setState({
            modelName: model.label,
            modelId: model.value,
            showModelModal: false,
        });
    }

    openReasonModal = () => {
        this.setState({
            showReasonModal: true,
        });
    }

    closeReasonModal = () => {
        this.setState({
            showReasonModal: false,
        });
    }

    selectReason = ( reason ) => {
        this.setState({
            reasonName: reason.name,
            reasonId: reason.id_,
            showReasonModal: false,
        });
    }

    openRemarkModal = () => {
        this.setState({
            showRemarkModal: true,
        });
    }

    closeRemarkModal = () => {
        this.setState({
            showRemarkModal: false,
        });
    }

    selectRemark = (remark) => {
        this.setState({
            assetRemark: remark.name,
            showRemarkModal: false,
        });
    }

    render() {
        return (
            <Formik
            initialValues={{ }}
            onSubmit={ values => this.submit(values) }
            >
            {({ handleChange, setFieldValue, handleBlur, handleSubmit, values }) => (
            <SafeAreaView style={styles.container}>
                <View style={styles.header}>
                    <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>
                        <TouchableOpacity onPress={() => this.back()}>
                            <Image source={ require('../images/back.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                        </TouchableOpacity>
                    </View>
                    <View style={{ width: getScreenWidth() - getPixel(110), justifyContent:'center', alignItems:'center' }}>
                        <Text style={{ fontSize: getPixel(17), color:'#333' }}>新增盘点</Text>
                    </View>
                    <View style={{ width: getPixel(55), justifyContent:'center', alignItems:'center'}}>
                    </View>
                </View>
               
                <ScrollView>
                    <View style={{ marginTop: getPixel(10) }}>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.inputLable }>盘点单名称</Text>
                            <TextInput style={ styles.inputValue} placeholder="请输入盘点名称" onChangeText={ text => this.handleChange({ inventoryName: text })}  value={ this.state.inventoryName } />
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>盘点部门</Text>
                            <TouchableOpacity onPress={this.openManageBranchModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.manageBranchName}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openManageBranchModal.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                        <View style={ styles.formGroup }>
                            <Text style={ styles.selectLable }>盘点人</Text>
                            <TouchableOpacity onPress={this.openManageUserModal.bind(this)}>
                                <Text style={ styles.selectValue }>{this.state.manageUserName}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openManageUserModal.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                    </View>
                    <View style={{ marginTop: getPixel(10),height: getPixel(100) }}>
                        <TextInput multiline  numberOfLines={6} returnKeyType='done' blurOnSubmit={true} style={{ textAlignVertical: 'top', backgroundColor:'#FFF', width: getScreenWidth(), paddingLeft: getPixel(10), paddingRight: getPixel(10), height: getPixel(100)}} placeholder="请输入备注" onChangeText={ text => this.handleChange({ remark: text })}  value={ this.state.remark } />
                    </View>
                    <View style={{ marginTop: getPixel(10) }}>
                    <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>盘点日期</Text>
                            <TouchableOpacity onPress={this.showDateTimePicker.bind(this)}>
                            <Text style={ styles.selectValue }>{this.state.finishDate}</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.showDateTimePicker.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                            
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>区域位置</Text>
                            <TouchableOpacity onPress={this.openAreaModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.areaName }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openAreaModal.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>类型</Text>
                            <TouchableOpacity onPress={this.openTypeModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.typeName }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openTypeModal.bind(this)}>
                                 <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>品牌</Text>
                            <TouchableOpacity onPress={this.openBrandModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.brandName }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openBrandModal.bind(this)}>
                                 <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>型号</Text>
                            <TouchableOpacity onPress={this.openModelModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.modelName }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openModelModal.bind(this)}>
                                 <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>状态</Text>
                            <TouchableOpacity onPress={this.openReasonModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.reasonName }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openReasonModal.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>        
                        <View style={ [styles.formGroup, { borderBottomColor: '#EEE', borderBottomWidth: getPixel(1) }] }>
                            <Text style={ styles.selectLable }>配置</Text>
                            <TouchableOpacity onPress={this.openRemarkModal.bind(this)}>
                                <Text style={ styles.selectValue }>{ this.state.assetRemark }</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={this.openRemarkModal.bind(this)}>
                                <Image style={ styles.selectIcon } source={ require('../images/select.png')}  style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                            </TouchableOpacity>
                        </View>        
                    </View>
                </ScrollView>
                <View style={styles.buttonGroup}>
                    <TouchableOpacity onPress={this.submit}>
                        <View style={styles.buttonAdd}>
                            <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>保存</Text>
                        </View>
                    </TouchableOpacity> 
                </View>
                <BranchTree treeData= {this.state.branchList} isVisible = { this.state.showManageBranchModal } closeModal={ this.closeManageBranchModal } selectNode={ this.selectManageBranch } onRequestClose={ this.closeManageBranchModal }/>
                <UserTree treeData= {this.state.selectUserList} isVisible = { this.state.showManageUserModal } closeModal={ this.closeManageUserModal } selectNode={ this.selectManageUser } onRequestClose={ this.closeManageUserModal }/>
                <Area data= {this.state.datacenterRoomTree} isVisible = { this.state.showAreaModal } closeModal={ this.closeAreaModal } selectNode={ this.selectArea }  onRequestClose={ this.closeAreaModal }/>
                <TypeTree treeData= {this.state.typeList} isVisible = { this.state.showTypeModal } closeModal={ this.closeTypeModal } selectNode={ this.selectType } onRequestClose={ this.closeTypeModal }/>
                <BrandTree treeData= {this.state.brandModeList} isVisible = { this.state.showBrandModal } closeModal={ this.closeBrandModal } selectNode={ this.selectBrand } onRequestClose={ this.closeBrandModal }/>
                <ModelTree treeData= {this.state.modeList} isVisible = { this.state.showModelModal } closeModal={ this.closeModelModal } selectNode={ this.selectModel } onRequestClose={ this.closeModelModal }/>
                <Reason data= {this.state.moveReasonList} isVisible = { this.state.showReasonModal } closeModal={ this.closeReasonModal } selectNode={ this.selectReason } onRequestClose={ this.closeReasonModal }/>
                <RemarkTree treeData= {this.state.remarkList} isVisible = { this.state.showRemarkModal } closeModal={ this.closeRemarkModal } selectNode={ this.selectRemark } onRequestClose={ this.closeRemarkModal }/>
                <DateTimePicker
                    cancelTextIOS='取消'
                    confirmTextIOS='确定'
                    titleIOS='盘点日期'
                    mode='date'
                    isVisible={this.state.isDateTimePickerVisible}
                    onConfirm={this.handleDatePicked}
                    onCancel={this.hideDateTimePicker}
                />
            </SafeAreaView>
             )}
             </Formik>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    header: {
        height: getPixel(50),
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        flexDirection: 'row',
    },
    formGroup: {
        flexDirection: 'row',
        alignItems: 'center',
        height: getPixel(50),
        backgroundColor: '#FFF',
        paddingLeft: getPixel(10),
        paddingRight: getPixel(10),
    },
    inputLable: {
        fontSize: getPixel(15),
        width: getPixel(90),
        color: '#333',
    },
    inputValue: {
        fontSize: getPixel(15),
        width: getScreenWidth() - getPixel(110),
    },
    selectLable: {
        fontSize: getPixel(15),
        width: getPixel(90),
        color: '#333',
    },
    selectValue: {
        fontSize: getPixel(15),
        width: getScreenWidth() - getPixel(130),
    },
    selectIcon: {
        width: getPixel(25),
        alignItems: 'center',
    },
    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(20),
        paddingRight: getPixel(20),
        height: getPixel(60), 
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
    },
    buttonAdd: {
        backgroundColor: '#4a69dd', 
        height: getPixel(40), 
        borderRadius: getPixel(10),
        width: (getScreenWidth() - 40),
    },
});